<template>
  <div class="security-report-container">
    <!-- 顶部工具栏 -->
    <div class="report-toolbar">
      <h2 class="page-title">
        <el-icon><el-icon-Document /></el-icon> 安全报告管理
      </h2>
      <div class="toolbar-actions">
        <!-- 生成新报告按钮 -->
        <el-button type="primary" @click="showGenerateDialog = true" class="generate-btn">
          <el-icon><el-icon-DocumentAdd /></el-icon>
          生成新报告
        </el-button>
        <!-- 数据来源切换 -->
        <el-switch
          v-model="useRealData"
          active-text="真实数据"
          inactive-text="模拟数据"
          @change="onDataSourceChange"
          class="data-source-switch"
        />
      </div>
    </div>

    <!-- 报告筛选和搜索 -->
    <div class="report-filter-section">
      <el-card shadow="hover" class="filter-card">
        <div class="filter-content">
          <div class="filter-header">
            <h3>报告筛选</h3>
            <div class="filter-actions">
              <el-button type="primary" @click="refreshReports">
                <el-icon><el-icon-Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </div>
          <!-- 日期范围筛选 -->
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateRangeShortcuts"
            @change="handleDateRangeChange"
            class="date-filter"
          />
          
          <!-- 报告类型筛选 -->
          <el-select v-model="reportTypeFilter" placeholder="选择报告类型" @change="filterReports" class="type-filter">
            <el-option label="全部类型" value=""></el-option>
            <el-option label="扫描报告" value="scan"></el-option>
            <el-option label="漏洞报告" value="vulnerability"></el-option>
            <el-option label="合规报告" value="compliance"></el-option>
            <el-option label="趋势报告" value="trend"></el-option>
          </el-select>
          
          <!-- 报告状态筛选 -->
          <el-select v-model="statusFilter" placeholder="选择报告状态" @change="filterReports" class="status-filter">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="生成中" value="generating"></el-option>
            <el-option label="已过期" value="expired"></el-option>
          </el-select>
          
          <!-- 搜索框 -->
          <el-input
            v-model="searchQuery"
            placeholder="搜索报告名称或扫描目标"
            prefix-icon="el-icon-Search"
            @input="handleSearch"
            class="search-input"
          />
          
          <!-- 高级筛选按钮 -->
          <el-button type="text" @click="showAdvancedFilter = !showAdvancedFilter" class="advanced-filter-btn">
            <el-icon><el-icon-Filter /></el-icon>
            高级筛选
          </el-button>
        </div>
        
        <!-- 高级筛选选项 -->
        <div v-if="showAdvancedFilter" class="advanced-filter-options">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-select v-model="severityFilter" placeholder="漏洞严重程度" @change="filterReports">
                <el-option label="全部严重程度" value=""></el-option>
                <el-option label="高危" value="high"></el-option>
                <el-option label="中危" value="medium"></el-option>
                <el-option label="低危" value="low"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="creatorFilter" placeholder="创建者" @change="filterReports">
                <el-option label="全部创建者" value=""></el-option>
                <el-option label="系统" value="system"></el-option>
                <el-option label="admin" value="admin"></el-option>
                <el-option label="user1" value="user1"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formatFilter" placeholder="报告格式" @change="filterReports">
                <el-option label="全部格式" value=""></el-option>
                <el-option label="PDF" value="pdf"></el-option>
                <el-option label="HTML" value="html"></el-option>
                <el-option label="Excel" value="excel"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="filterReports" class="apply-filter-btn">应用筛选</el-button>
              <el-button type="text" @click="resetFilters" class="reset-filter-btn">重置</el-button>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 报告列表 -->
    <div class="report-list-section">
      <el-card shadow="hover" class="report-list-card">
        <template #header>
          <div class="report-list-header">
            <span>报告列表</span>
            <span class="report-count">共 {{ filteredReports.length }} 个报告</span>
          </div>
        </template>
        
        <!-- 报告表格 -->
        <el-table 
          v-loading="isLoading" 
          :data="paginatedReports || []" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          class="report-table"
          empty-text="暂无报告数据"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="报告名称" min-width="200">
            <template #default="scope">
              <div class="report-name-wrapper">
                <span class="report-name">{{ scope.row.name }}</span>
                <el-tag v-if="scope.row.isUrgent" size="small" type="danger" class="urgent-tag">紧急</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="报告类型" width="120">
            <template #default="scope">
              <el-tag size="small" :type="getReportTypeTagType(scope.row.type)">
                {{ getReportTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="target" label="关联目标" width="180" />
          <el-table-column prop="vulnerabilityCount" label="漏洞数量" width="100" align="center">
            <template #default="scope">
              <div class="vulnerability-stats">
                <span class="total-vulns">{{ scope.row.vulnerabilityCount || 0 }}</span>
                <div v-if="scope.row.vulnerabilityStats" class="vulnerability-breakdown">
                  <span class="high-vuln" :style="{ opacity: scope.row.vulnerabilityStats.high > 0 ? 1 : 0.3 }">
                    高危: {{ scope.row.vulnerabilityStats.high || 0 }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag size="small" :type="getReportStatusTagType(scope.row.status)">
                {{ getReportStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" :formatter="formatDateTime" />
          <el-table-column prop="creator" label="创建者" width="100" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 'completed'" 
                type="primary" 
                size="small" 
                @click="previewReport(scope.row)"
                class="preview-btn"
              >
                <el-icon><el-icon-ZoomIn /></el-icon> 预览
              </el-button>
              <el-button 
                v-if="scope.row.status === 'completed'" 
                size="small" 
                @click="downloadReport(scope.row)"
                class="download-btn"
              >
                <el-icon><el-icon-Download /></el-icon> 下载
              </el-button>
              <el-button 
                v-if="scope.row.status === 'generating'" 
                disabled 
                size="small"
                class="generating-btn"
              >
                生成中...
              </el-button>
              <el-dropdown trigger="click" class="more-actions">
                <el-button size="small" type="text">
                  更多 <el-icon class="el-icon--right"><el-icon-CaretBottom /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="duplicateReport(scope.row)">
                      <el-icon><el-icon-CopyDocument /></el-icon> 复制
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteReport(scope.row)" danger>
                      <el-icon><el-icon-Delete /></el-icon> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredReports.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedReports.length > 0" class="batch-operations">
      <el-card shadow="hover" class="batch-actions-card">
        <div class="batch-actions-content">
          <span>已选择 {{ selectedReports.length }} 个报告</span>
          <div class="batch-actions-buttons">
            <el-button type="primary" @click="batchDownloadReports" class="batch-download-btn">
              <el-icon><el-icon-Download /></el-icon>
              批量下载
            </el-button>
            <el-button type="danger" @click="batchDeleteReports" class="batch-delete-btn">
              <el-icon><el-icon-Delete /></el-icon>
              批量删除
            </el-button>
            <el-button type="text" @click="clearSelection" class="clear-selection-btn">
              取消选择
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 生成报告对话框 -->
    <el-dialog
      v-model="showGenerateDialog"
      title="生成新报告"
      width="600px"
      :before-close="handleGenerateDialogClose"
    >
      <el-form :model="newReportForm" :rules="newReportRules" ref="newReportFormRef" label-width="120px">
        <el-form-item label="报告名称" prop="name">
          <el-input v-model="newReportForm.name" placeholder="请输入报告名称" />
        </el-form-item>
        <el-form-item label="报告类型" prop="type">
          <el-select v-model="newReportForm.type" placeholder="请选择报告类型">
            <el-option label="扫描报告" value="scan"></el-option>
            <el-option label="漏洞报告" value="vulnerability"></el-option>
            <el-option label="合规报告" value="compliance"></el-option>
            <el-option label="趋势报告" value="trend"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报告格式" prop="format">
          <el-select v-model="newReportForm.format" placeholder="请选择报告格式">
            <el-option label="PDF" value="pdf"></el-option>
            <el-option label="HTML" value="html"></el-option>
            <el-option label="Excel" value="excel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报告范围" prop="scope">
          <el-radio-group v-model="newReportForm.scope">
            <el-radio value="all">全部扫描结果</el-radio>
            <el-radio value="dateRange">指定日期范围</el-radio>
            <el-radio value="specificScan">特定扫描任务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="newReportForm.scope === 'dateRange'" label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="newReportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item v-if="newReportForm.scope === 'specificScan'" label="扫描任务" prop="scanTaskId">
          <el-select v-model="newReportForm.scanTaskId" placeholder="请选择扫描任务" style="width: 100%">
            <el-option 
              v-for="task in scanTasks" 
              :key="task.id" 
              :label="task.target" 
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报告选项">
          <el-checkbox-group v-model="newReportForm.options">
            <el-checkbox label="includeDetailedVulnerability">包含详细漏洞信息</el-checkbox>
            <el-checkbox label="includeRemediationSteps">包含修复建议</el-checkbox>
            <el-checkbox label="includeExecutiveSummary">包含执行摘要</el-checkbox>
            <el-checkbox label="includeCharts">包含图表</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="严重程度过滤">
          <el-checkbox-group v-model="newReportForm.severityFilters">
            <el-checkbox label="high">高危</el-checkbox>
            <el-checkbox label="medium">中危</el-checkbox>
            <el-checkbox label="low">低危</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showGenerateDialog = false">取消</el-button>
        <el-button type="primary" @click="generateReport" :loading="isGeneratingReport">生成报告</el-button>
      </template>
    </el-dialog>

    <!-- 报告预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="previewReportData?.name || '报告预览'"
      width="80%"
      fullscreen
    >
      <div class="report-preview-container" v-loading="isLoadingPreview">
        <div v-if="previewReportData" class="report-preview-content">
          <!-- 报告头部 -->
          <div class="report-preview-header">
            <h1 class="preview-report-title">{{ previewReportData.name }}</h1>
            <div class="preview-report-meta">
              <span class="meta-item">报告类型: {{ getReportTypeName(previewReportData.type) }}</span>
              <span class="meta-item">生成时间: {{ formatDateTime(previewReportData.createdAt) }}</span>
              <span class="meta-item">创建者: {{ previewReportData.creator }}</span>
            </div>
          </div>
          
          <!-- 报告摘要 -->
          <div class="report-preview-summary">
            <h2>执行摘要</h2>
            <div class="summary-content">
              <p>本报告基于 {{ previewReportData.vulnerabilityCount || 0 }} 个发现的漏洞生成，其中包括 {{ previewReportData.vulnerabilityStats?.high || 0 }} 个高危漏洞、{{ previewReportData.vulnerabilityStats?.medium || 0 }} 个中危漏洞和 {{ previewReportData.vulnerabilityStats?.low || 0 }} 个低危漏洞。</p>
              <p>建议优先修复高危漏洞，以降低系统安全风险。</p>
            </div>
          </div>
          
          <!-- 漏洞统计 -->
          <div class="report-preview-stats">
            <h2>漏洞统计</h2>
            <div class="stats-grid">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon danger">
                    <el-icon><el-icon-Fire /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>高危漏洞</h3>
                    <p class="stat-value">{{ previewReportData.vulnerabilityStats?.high || 0 }}</p>
                  </div>
                </div>
              </el-card>
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon warning">
                    <el-icon><el-icon-Warning /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>中危漏洞</h3>
                    <p class="stat-value">{{ previewReportData.vulnerabilityStats?.medium || 0 }}</p>
                  </div>
                </div>
              </el-card>
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon info">
                    <el-icon><el-icon-InfoFilled /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>低危漏洞</h3>
                    <p class="stat-value">{{ previewReportData.vulnerabilityStats?.low || 0 }}</p>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
          
          <!-- 漏洞列表 -->
          <div class="report-preview-vulnerabilities">
            <h2>漏洞详情</h2>
            <el-table :data="previewReportData.vulnerabilities || []" style="width: 100%">
              <el-table-column prop="name" label="漏洞名称" />
              <el-table-column prop="severity" label="严重程度">
                <template #default="scope">
                  <el-tag size="small" :type="getSeverityTagType(scope.row.severity)">
                    {{ getSeverityName(scope.row.severity) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="target" label="受影响目标" />
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
              <el-table-column prop="recommendation" label="修复建议" show-overflow-tooltip />
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
        <el-button type="primary" @click="downloadReport(previewReportData)">下载报告</el-button>
      </template>
    </el-dialog>

    <!-- 报告生成进度对话框 -->
    <el-dialog
      v-model="showProgressDialog"
      title="报告生成中"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="progress-dialog-content">
        <el-progress :percentage="reportGenerationProgress" :status="getProgressStatus" />
        <p class="progress-message">{{ reportGenerationMessage }}</p>
        <el-button v-if="reportGenerationProgress > 0 && reportGenerationProgress < 100" type="text" @click="cancelReportGeneration">
          取消生成
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import apiService from '../services/apiService'

// 添加刷新报告方法
const refreshReports = async () => {
  try {
    isLoading.value = true
    await loadReports()
  } catch (error) {
    console.error('刷新报告失败:', error)
    ElMessage.error('刷新数据失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const router = useRouter()

// 数据来源控制
const useRealData = ref(false)

// 报告列表数据
const reports = ref([])
const isLoading = ref(false)
const searchQuery = ref('')
const dateRange = ref(null)
const reportTypeFilter = ref('')
const statusFilter = ref('')
const severityFilter = ref('')
const creatorFilter = ref('')
const formatFilter = ref('')
const showAdvancedFilter = ref(false)
const selectedReports = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 报告生成相关
const showGenerateDialog = ref(false)
const showPreviewDialog = ref(false)
const showProgressDialog = ref(false)
const isGeneratingReport = ref(false)
const reportGenerationProgress = ref(0)
const reportGenerationMessage = ref('')
const previewReportData = ref(null)
const isLoadingPreview = ref(false)
const scanTasks = ref([])

// 新报告表单
const newReportForm = ref({
  name: '',
  type: 'vulnerability',
  format: 'pdf',
  scope: 'all',
  dateRange: null,
  scanTaskId: '',
  options: ['includeDetailedVulnerability', 'includeRemediationSteps'],
  severityFilters: ['high', 'medium', 'low']
})

const newReportRules = {
  name: [
    { required: true, message: '请输入报告名称', trigger: 'blur' },
    { min: 3, max: 100, message: '报告名称长度应在 3 到 100 个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择报告类型', trigger: 'change' }
  ],
  format: [
    { required: true, message: '请选择报告格式', trigger: 'change' }
  ],
  dateRange: [
    { required: () => newReportForm.value.scope === 'dateRange', message: '请选择日期范围', trigger: 'change' }
  ],
  scanTaskId: [
    { required: () => newReportForm.value.scope === 'specificScan', message: '请选择扫描任务', trigger: 'change' }
  ]
}

const newReportFormRef = ref(null)

// 日期范围快捷选项
const dateRangeShortcuts = [
  { text: '今天', value: () => [new Date(), new Date()] },
  { text: '昨天', value: () => {
      const yesterday = new Date()
      yesterday.setTime(yesterday.getTime() - 3600 * 1000 * 24)
      return [yesterday, yesterday]
    }
  },
  { text: '近7天', value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  { text: '近30天', value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 计算属性：筛选后的报告列表
const filteredReports = computed(() => {
  return reports.value.filter(report => {
    // 搜索查询筛选
    const matchesSearch = !searchQuery.value || 
      report.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      (report.target && report.target.toLowerCase().includes(searchQuery.value.toLowerCase()))
    
    // 日期范围筛选
    const matchesDateRange = !dateRange.value || 
      (!report.createdAt || 
        (new Date(report.createdAt) >= dateRange.value[0] && 
         new Date(report.createdAt) <= dateRange.value[1]))
    
    // 报告类型筛选
    const matchesType = !reportTypeFilter.value || report.type === reportTypeFilter.value
    
    // 状态筛选
    const matchesStatus = !statusFilter.value || report.status === statusFilter.value
    
    // 严重程度筛选
    const matchesSeverity = !severityFilter.value || 
      (report.vulnerabilityStats && report.vulnerabilityStats[severityFilter.value] > 0)
    
    // 创建者筛选
    const matchesCreator = !creatorFilter.value || report.creator === creatorFilter.value
    
    // 格式筛选
    const matchesFormat = !formatFilter.value || report.format === formatFilter.value
    
    return matchesSearch && matchesDateRange && matchesType && matchesStatus && 
           matchesSeverity && matchesCreator && matchesFormat
  })
})

// 计算属性：分页后的报告列表
const paginatedReports = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredReports.value.slice(start, end)
})

// 计算属性：报告生成进度状态
const getProgressStatus = computed(() => {
  if (reportGenerationProgress.value >= 100) return 'success'
  return 'active'
})

// 初始化数据
const initializeData = async () => {
  try {
    isLoading.value = true
    await Promise.all([
      loadReports(),
      loadScanTasks()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 加载报告列表
const loadReports = async () => {
  try {
    if (useRealData.value) {
      // 尝试从API获取真实数据
      const response = await apiService.getReports()
      reports.value = response.data || []
    } else {
      // 使用模拟数据
      reports.value = generateMockReports()
    }
  } catch (error) {
    console.error('加载报告失败:', error)
    // 如果真实数据获取失败，回退到模拟数据
    reports.value = generateMockReports()
  }
}

// 加载扫描任务列表
const loadScanTasks = async () => {
  try {
    if (useRealData.value) {
      const response = await apiService.getScanTasks()
      scanTasks.value = response.data || []
    } else {
      // 使用模拟数据
      scanTasks.value = [
        { id: 1, target: 'https://example.com', status: 'completed' },
        { id: 2, target: 'https://test.org', status: 'completed' },
        { id: 3, target: 'https://sample.net', status: 'completed' },
        { id: 4, target: 'https://demo.com', status: 'completed' }
      ]
    }
  } catch (error) {
    console.error('加载扫描任务失败:', error)
    // 如果真实数据获取失败，回退到模拟数据
    scanTasks.value = [
      { id: 1, target: 'https://example.com', status: 'completed' },
      { id: 2, target: 'https://test.org', status: 'completed' },
      { id: 3, target: 'https://sample.net', status: 'completed' },
      { id: 4, target: 'https://demo.com', status: 'completed' }
    ]
  }
}

// 生成模拟报告数据
const generateMockReports = () => {
  const now = new Date()
  const mockReports = [
    {
      id: 1,
      name: '每周安全漏洞汇总报告',
      type: 'vulnerability',
      format: 'pdf',
      target: '所有系统',
      status: 'completed',
      creator: 'system',
      createdAt: new Date(now.getTime() - 3600 * 1000 * 24),
      vulnerabilityCount: 24,
      vulnerabilityStats: {
        high: 3,
        medium: 12,
        low: 9
      },
      isUrgent: true
    },
    {
      id: 2,
      name: '网站扫描报告 - example.com',
      type: 'scan',
      format: 'html',
      target: 'https://example.com',
      status: 'completed',
      creator: 'admin',
      createdAt: new Date(now.getTime() - 3600 * 1000 * 48),
      vulnerabilityCount: 12,
      vulnerabilityStats: {
        high: 1,
        medium: 5,
        low: 6
      }
    },
    {
      id: 3,
      name: '安全合规性检查报告',
      type: 'compliance',
      format: 'pdf',
      target: '所有系统',
      status: 'completed',
      creator: 'admin',
      createdAt: new Date(now.getTime() - 3600 * 1000 * 72),
      vulnerabilityCount: 8,
      vulnerabilityStats: {
        high: 0,
        medium: 3,
        low: 5
      }
    },
    {
      id: 4,
      name: '月度安全趋势报告',
      type: 'trend',
      format: 'excel',
      target: '所有系统',
      status: 'completed',
      creator: 'system',
      createdAt: new Date(now.getTime() - 3600 * 1000 * 24 * 7),
      vulnerabilityCount: 45,
      vulnerabilityStats: {
        high: 5,
        medium: 20,
        low: 20
      }
    },
    {
      id: 5,
      name: '测试报告 - 正在生成',
      type: 'scan',
      format: 'pdf',
      target: 'https://test.org',
      status: 'generating',
      creator: 'user1',
      createdAt: new Date(now.getTime() - 3600 * 1000),
      vulnerabilityCount: 0,
      vulnerabilityStats: {
        high: 0,
        medium: 0,
        low: 0
      }
    },
    {
      id: 6,
      name: '过时的扫描报告',
      type: 'scan',
      format: 'pdf',
      target: 'https://old.example.com',
      status: 'expired',
      creator: 'admin',
      createdAt: new Date(now.getTime() - 3600 * 1000 * 24 * 30),
      vulnerabilityCount: 15,
      vulnerabilityStats: {
        high: 2,
        medium: 6,
        low: 7
      }
    }
  ]
  return mockReports
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取报告类型标签类型
const getReportTypeTagType = (type) => {
  const typeMap = {
    'scan': 'primary',
    'vulnerability': 'danger',
    'compliance': 'warning',
    'trend': 'info'
  }
  return typeMap[type] || 'default'
}

// 获取报告类型名称
const getReportTypeName = (type) => {
  const typeMap = {
    'scan': '扫描报告',
    'vulnerability': '漏洞报告',
    'compliance': '合规报告',
    'trend': '趋势报告'
  }
  return typeMap[type] || type
}

// 获取报告状态标签类型
const getReportStatusTagType = (status) => {
  const statusMap = {
    'completed': 'success',
    'generating': 'warning',
    'expired': 'default'
  }
  return statusMap[status] || 'default'
}

// 获取报告状态名称
const getReportStatusName = (status) => {
  const statusMap = {
    'completed': '已完成',
    'generating': '生成中',
    'expired': '已过期'
  }
  return statusMap[status] || status
}

// 获取严重程度标签类型
const getSeverityTagType = (severity) => {
  const severityMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return severityMap[severity] || 'default'
}

// 获取严重程度名称
const getSeverityName = (severity) => {
  const severityMap = {
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return severityMap[severity] || severity
}

// 处理搜索
const handleSearch = (value) => {
  // 防抖处理
  clearTimeout(window.searchTimeout)
  window.searchTimeout = setTimeout(() => {
    searchQuery.value = value
    currentPage.value = 1
  }, 300)
}

// 处理日期范围变化
const handleDateRangeChange = (value) => {
  dateRange.value = value
  currentPage.value = 1
}

// 筛选报告
const filterReports = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  dateRange.value = null
  reportTypeFilter.value = ''
  statusFilter.value = ''
  severityFilter.value = ''
  creatorFilter.value = ''
  formatFilter.value = ''
  currentPage.value = 1
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedReports.value = selection
}

// 清除选择
const clearSelection = () => {
  selectedReports.value = []
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 生成报告
const generateReport = async () => {
  try {
    // 验证表单
    await newReportFormRef.value.validate()
    
    isGeneratingReport.value = true
    showGenerateDialog.value = false
    showProgressDialog.value = true
    reportGenerationProgress.value = 0
    reportGenerationMessage.value = '正在准备报告数据...'
    
    // 模拟报告生成进度
    const progressInterval = setInterval(() => {
      reportGenerationProgress.value += Math.floor(Math.random() * 10) + 5
      
      if (reportGenerationProgress.value <= 30) {
        reportGenerationMessage.value = '正在收集数据...'
      } else if (reportGenerationProgress.value <= 60) {
        reportGenerationMessage.value = '正在分析漏洞...'
      } else if (reportGenerationProgress.value <= 80) {
        reportGenerationMessage.value = '正在生成报告...'
      } else {
        reportGenerationMessage.value = '正在格式化报告...'
      }
      
      if (reportGenerationProgress.value >= 100) {
        clearInterval(progressInterval)
        reportGenerationProgress.value = 100
        reportGenerationMessage.value = '报告生成完成！'
        
        // 模拟报告生成延迟
        setTimeout(() => {
          showProgressDialog.value = false
          isGeneratingReport.value = false
          
          // 添加新报告到列表
          const newReport = {
            id: Date.now(),
            name: newReportForm.value.name,
            type: newReportForm.value.type,
            format: newReportForm.value.format,
            target: newReportForm.value.scope === 'specificScan' ? 
              scanTasks.value.find(task => task.id === newReportForm.value.scanTaskId)?.target || '未知目标' : 
              '所有系统',
            status: 'completed',
            creator: 'admin',
            createdAt: new Date(),
            vulnerabilityCount: Math.floor(Math.random() * 30) + 5,
            vulnerabilityStats: {
              high: Math.floor(Math.random() * 5),
              medium: Math.floor(Math.random() * 15) + 5,
              low: Math.floor(Math.random() * 10) + 5
            }
          }
          
          reports.value.unshift(newReport)
          
          // 重置表单
          resetNewReportForm()
          
          ElMessage.success('报告生成成功！')
          
          // 自动预览新生成的报告
          previewReport(newReport)
        }, 1000)
      }
    }, 500)
    
    // 保存进度间隔引用以便取消
    window.reportGenerationInterval = progressInterval
    
  } catch (error) {
    isGeneratingReport.value = false
    showProgressDialog.value = false
    if (error !== false) { // 避免表单验证失败的错误
      console.error('生成报告失败:', error)
      ElMessage.error('生成报告失败，请稍后重试')
    }
  }
}

// 取消报告生成
const cancelReportGeneration = () => {
  ElMessageBox.confirm(
    '确定要取消报告生成吗？',
    '取消报告生成',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    if (window.reportGenerationInterval) {
      clearInterval(window.reportGenerationInterval)
    }
    showProgressDialog.value = false
    isGeneratingReport.value = false
    ElMessage.info('已取消报告生成')
  }).catch(() => {
    // 取消操作
  })
}

// 重置新报告表单
const resetNewReportForm = () => {
  newReportForm.value = {
    name: '',
    type: 'vulnerability',
    format: 'pdf',
    scope: 'all',
    dateRange: null,
    scanTaskId: '',
    options: ['includeDetailedVulnerability', 'includeRemediationSteps'],
    severityFilters: ['high', 'medium', 'low']
  }
  if (newReportFormRef.value) {
    newReportFormRef.value.resetFields()
  }
}

// 处理生成报告对话框关闭
const handleGenerateDialogClose = () => {
  resetNewReportForm()
}

// 预览报告
const previewReport = async (report) => {
  try {
    isLoadingPreview.value = true
    showPreviewDialog.value = true
    
    // 生成模拟的报告详细数据
    const mockVulnerabilities = [
      {
        name: 'SQL注入漏洞',
        severity: 'high',
        target: `${report.target}/api/login`,
        description: '在登录接口中发现SQL注入漏洞，攻击者可能通过构造恶意输入获取数据库信息。',
        recommendation: '使用参数化查询或预编译语句，避免直接拼接SQL语句。'
      },
      {
        name: '跨站脚本攻击(XSS)',
        severity: 'medium',
        target: `${report.target}/profile`,
        description: '用户资料页面存在XSS漏洞，攻击者可以注入恶意脚本。',
        recommendation: '对用户输入进行严格过滤和转义，实施内容安全策略(CSP)。'
      },
      {
        name: '弱密码策略',
        severity: 'low',
        target: `${report.target}/register`,
        description: '注册页面密码策略过于宽松，允许设置简单密码。',
        recommendation: '加强密码复杂度要求，包括长度、大小写字母、数字和特殊字符。'
      }
    ]
    
    // 根据报告类型和严重程度筛选模拟漏洞
    let vulnerabilities = []
    if (report.vulnerabilityStats?.high > 0) {
      vulnerabilities.push(...mockVulnerabilities.filter(v => v.severity === 'high').slice(0, report.vulnerabilityStats.high))
    }
    if (report.vulnerabilityStats?.medium > 0) {
      vulnerabilities.push(...mockVulnerabilities.filter(v => v.severity === 'medium').slice(0, report.vulnerabilityStats.medium))
    }
    if (report.vulnerabilityStats?.low > 0) {
      vulnerabilities.push(...mockVulnerabilities.filter(v => v.severity === 'low').slice(0, report.vulnerabilityStats.low))
    }
    
    // 填充预览数据
    previewReportData.value = {
      ...report,
      vulnerabilities
    }
    
  } catch (error) {
    console.error('预览报告失败:', error)
    ElMessage.error('加载报告内容失败，请稍后重试')
    showPreviewDialog.value = false
  } finally {
    isLoadingPreview.value = false
  }
}

// 下载报告
const downloadReport = (report) => {
  // 模拟下载
  ElMessage.success(`正在下载 ${report.name}...`)
  
  // 在实际应用中，这里应该调用API获取报告文件
  setTimeout(() => {
    ElMessage.success('报告下载成功！')
  }, 1000)
}

// 复制报告
const duplicateReport = (report) => {
  showGenerateDialog.value = true
  newReportForm.value = {
    name: `${report.name} (副本)`,
    type: report.type,
    format: report.format,
    scope: 'all',
    dateRange: null,
    scanTaskId: '',
    options: ['includeDetailedVulnerability', 'includeRemediationSteps'],
    severityFilters: ['high', 'medium', 'low']
  }
}

// 删除报告
const deleteReport = (report) => {
  ElMessageBox.confirm(
    `确定要删除报告「${report.name}」吗？此操作不可恢复。`,
    '删除报告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    // 删除报告
    const index = reports.value.findIndex(r => r.id === report.id)
    if (index !== -1) {
      reports.value.splice(index, 1)
    }
    ElMessage.success('报告已成功删除')
  }).catch(() => {
    // 取消操作
  })
}

// 批量下载报告
const batchDownloadReports = () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要下载的报告')
    return
  }
  
  ElMessage.success(`正在批量下载 ${selectedReports.value.length} 个报告...`)
  // 模拟批量下载
  setTimeout(() => {
    ElMessage.success('批量下载完成！')
  }, 1500)
}

// 批量删除报告
const batchDeleteReports = () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要删除的报告')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedReports.value.length} 个报告吗？此操作不可恢复。`,
    '批量删除报告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    // 批量删除报告
    const selectedIds = selectedReports.value.map(report => report.id)
    reports.value = reports.value.filter(report => !selectedIds.includes(report.id))
    selectedReports.value = []
    ElMessage.success('报告已成功删除')
  }).catch(() => {
    // 取消操作
  })
}

// 处理数据源切换
const onDataSourceChange = () => {
  ElMessage.info(`已切换到${useRealData.value ? '真实' : '模拟'}数据模式`)
  loadReports()
  loadScanTasks()
}

// 监听数据源变化
watch(useRealData, onDataSourceChange)

// 组件挂载时初始化数据
onMounted(() => {
  initializeData()
})
</script>

<style scoped>
.security-report-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部工具栏 */
.report-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.generate-btn {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.data-source-switch {
  font-size: 14px;
}

/* 筛选区域 */
.report-filter-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 8px;
  overflow: hidden;
}

.filter-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.date-filter,
.type-filter,
.status-filter {
  width: 200px;
}

.search-input {
  width: 300px;
}

.advanced-filter-btn {
  white-space: nowrap;
}

.advanced-filter-options {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

.apply-filter-btn,
.reset-filter-btn {
  margin-right: 8px;
}

/* 报告列表 */
.report-list-section {
  margin-bottom: 24px;
}

.report-list-card {
  border-radius: 8px;
  overflow: hidden;
}

.report-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.report-count {
  font-size: 14px;
  color: #6b7280;
  font-weight: normal;
}

.report-table {
  margin-top: 16px;
}

.report-name-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.report-name {
  font-weight: 500;
}

.urgent-tag {
  font-size: 10px;
}

.vulnerability-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.total-vulns {
  font-weight: 600;
  font-size: 16px;
}

.vulnerability-breakdown {
  font-size: 12px;
}

.high-vuln {
  color: #ef4444;
}

.preview-btn,
.download-btn {
  margin-right: 8px;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 批量操作 */
.batch-operations {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 40px);
  max-width: 1400px;
  z-index: 100;
}

.batch-actions-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.batch-actions-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions-buttons {
  display: flex;
  gap: 12px;
}

/* 报告预览 */
.report-preview-container {
  padding: 20px;
}

.report-preview-header {
  text-align: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e5e7eb;
}

.preview-report-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 16px;
}

.preview-report-meta {
  display: flex;
  justify-content: center;
  gap: 32px;
  color: #6b7280;
}

.meta-item {
  font-size: 14px;
}

.report-preview-summary {
  margin-bottom: 40px;
}

.report-preview-summary h2 {
  font-size: 22px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
}

.summary-content {
  background-color: #f9fafb;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.summary-content p {
  margin-bottom: 12px;
  line-height: 1.6;
}

.report-preview-stats {
  margin-bottom: 40px;
}

.report-preview-stats h2 {
  font-size: 22px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  border-radius: 8px;
  overflow: hidden;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.danger {
  background-color: #ef4444;
}

.stat-icon.warning {
  background-color: #f59e0b;
}

.stat-icon.info {
  background-color: #3b82f6;
}

.stat-info h3 {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
  font-weight: normal;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
}

.report-preview-vulnerabilities h2 {
  font-size: 22px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 20px;
}

/* 进度对话框 */
.progress-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.progress-message {
  margin-top: 16px;
  color: #6b7280;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .security-report-container {
    padding: 10px;
  }
  
  .report-toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .date-filter,
  .type-filter,
  .status-filter,
  .search-input {
    width: 100%;
  }
  
  .preview-report-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .batch-operations {
    width: calc(100% - 20px);
  }
  
  .batch-actions-content {
    flex-direction: column;
    gap: 12px;
  }
}
</style>